//
//  Wrapper.m
//  SoundOutputter
//
//  Created by Pierre DUCHENE on 10/02/10.
//  Copyright 2010 Pierre DUCHENE. All rights reserved.
//

#import "AudioWrapper.h"
#include "CPPOutput.h"
#import "SignalVisualizer.h"
#import "SynthKit.h"
#import "System.h"

@implementation AudioWrapper

#pragma mark -
#pragma mark Singleton Implementation
static AudioWrapper *sharedAudioWrapper = nil;

+ (AudioWrapper*)sharedWrapper
{
    if (sharedAudioWrapper == nil) {
        sharedAudioWrapper = [[super allocWithZone:NULL] init];
    }
	
    return sharedAudioWrapper;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedWrapper] retain];
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

#pragma mark -
#pragma mark Access to C++ Module
- (void)clearBuffer
{
	ClearBuffer();
}

- (void)displayBuffer
{
	DisplayBuffer();
}

- (NSArray*)buffer
{	
	float* buffer = GetBuffer();
	unsigned int size = GetSize();
	NSMutableArray* result = [[NSMutableArray alloc] init];
	for (unsigned int i = 0; i < size; i++) {
		[result addObject:[NSNumber numberWithFloat:buffer[i]]];
	}
	
	return [NSArray arrayWithArray:[result autorelease]];
}

- (NSInteger) bufferOutputIndex{
	NSInteger currentBufferOutputIndex = getbufferOutputIndex();
	return currentBufferOutputIndex;
}

- (void)addDataToBuffer:(NSArray*)theData
{
	unsigned int size = [theData count];
	float* floatData = (float*)malloc(size * sizeof(float));
	for (unsigned int i = 0; i < size; i++) {
		floatData[i] = [[theData objectAtIndex:i] floatValue];
	}
	AddDataToBuffer(floatData, size);
	free(floatData);
}

- (void)openOutput
{
	OpenOutput();
}

- (void)startOutput
{
	Start();
}

- (void)stopOutput
{
	Stop();
}

- (void)closeOutput
{
	CloseOutput();
}

#pragma mark -
#pragma mark initMethods

@end
